﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Dynamic;
using Trade.ExChangeSrv;

namespace TradeWeb.Controllers
{
    public class ExChangeSrvController : Controller
    {
        public string GetExChangeRate()
        {
            string jsonResult = string.Empty;
            DataSet dsResult = new DataSet();

            DataTable dtExchange=new DataTable();
            DataRow[] drSelectRows;

            decimal decUSDToRMBRate;
            decimal decBuyingRate;
            string strCurr = string.Empty;

            try
            {
                dtExchange = new ExchangeSrv().GetCurrencyExchangeList();
            }
            catch (Exception ex)
            {
                jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"" + ex.Message + "\"}";
            }

            drSelectRows = dtExchange.Select("CurrencyName = 'USD'");
            if (drSelectRows.Length==0)
            {
                return jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"未能获取到美金汇率！\"}";
            }
            decUSDToRMBRate = drSelectRows[0]["BuyingRate"] == DBNull.Value ? 0 : (decimal)drSelectRows[0]["BuyingRate"];
            decUSDToRMBRate /= 100;

            //更新币别表RMB记录信息
            List<string> lstUpdate = new List<string>();
            string strUpdateRMB = "UPDATE T_DictValue SET RMBRate = 1,USDRate = " + (1 / decUSDToRMBRate).ToString() + " WHERE DictName='币别' AND CNName = 'RMB'";
            lstUpdate.Add(strUpdateRMB);

            //更新币别表USD记录信息
            string strUpdateUSD = "UPDATE T_DictValue SET RMBRate = " + decUSDToRMBRate.ToString() + ",USDRate = 1 WHERE  DictName='币别' AND CNName = 'USD'";
            lstUpdate.Add(strUpdateUSD);

            //更新币别表ERU、JPY等其他币别的信息
            foreach (DataRow drRow in dtExchange.Rows)
            {
                strCurr = drRow["CurrencyName"].ToString();
                if (strCurr.Trim().ToLower() == "RMB".Trim().ToLower() || strCurr.Trim().ToLower() == "USD".Trim().ToLower())
                    continue;
                decBuyingRate = drRow["BuyingRate"] == DBNull.Value ? 0 : (decimal)drRow["BuyingRate"];
                decBuyingRate /= 100;
                string strUpdateCurrOther = "UPDATE T_DictValue SET RMBRate = " + decBuyingRate.ToString() + ",USDRate=" + (decBuyingRate / decUSDToRMBRate).ToString() + " WHERE  DictName='币别' AND CNName = '" + strCurr.Replace("'", "''") + "'";
                lstUpdate.Add(strUpdateCurrOther);
            }

            SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
            SqlCommand sqlComUpdate;
            SqlCommand sqlComSearch;
            DataSet dsViewData = new DataSet();
            try
            {
                sqlConn.Open();
                SqlTransaction sqlTran = sqlConn.BeginTransaction();
                for (int i = 0; i < lstUpdate.Count; i++)
                {
                    sqlComUpdate = new SqlCommand(lstUpdate[i], sqlConn);
                    sqlComUpdate.Transaction = sqlTran;
                    sqlComUpdate.ExecuteNonQuery();
                }

                string strSQLSearch = "SELECT DictName,ENName,SortID,RMBRate,USDRate  FROM V_Curr WHERE ISDel=0 ORDER BY SortID";
                sqlComSearch = new SqlCommand(strSQLSearch, sqlConn);
                sqlComSearch.Transaction = sqlTran;
                SqlDataAdapter sqlAdaSearch = new SqlDataAdapter(sqlComSearch);
                sqlAdaSearch.Fill(dsViewData, "V_Curr");
                
                //提交事务
                sqlTran.Commit();


                //从视图V_Curr中，再重新获取一下，各个币种的转人民币、美元汇率
                DataTable dtRateTemp = new DataTable();
                dtRateTemp.Columns.Add("DictName",typeof(string));
                dtRateTemp.Columns.Add("ENName", typeof(string));
                dtRateTemp.Columns.Add("SortID", typeof(System.Int32));
                dtRateTemp.Columns.Add("RMBRate", typeof(string));
                dtRateTemp.Columns.Add("USDRate", typeof(string));

                for (int i = 0; i < dsViewData.Tables["V_Curr"].DefaultView.Count; i++)
                {
                    DataRow drNew = dtRateTemp.NewRow();
                    drNew["DictName"] = dsViewData.Tables["V_Curr"].DefaultView[i]["DictName"].ToString();
                    drNew["ENName"] = dsViewData.Tables["V_Curr"].DefaultView[i]["ENName"].ToString();
                    drNew["SortID"] = dsViewData.Tables["V_Curr"].DefaultView[i]["SortID"].ToString();

                    decimal decRMBRate = dsViewData.Tables["V_Curr"].DefaultView[i]["RMBRate"] == DBNull.Value ? 0 : (decimal)dsViewData.Tables["V_Curr"].DefaultView[i]["RMBRate"];
                    drNew["RMBRate"] = decRMBRate.ToString("#0.000000");
                    decimal decUSDRate = dsViewData.Tables["V_Curr"].DefaultView[i]["USDRate"] == DBNull.Value ? 0 : (decimal)dsViewData.Tables["V_Curr"].DefaultView[i]["USDRate"];
                    drNew["USDRate"] = decUSDRate.ToString("#0.000000");
                    dtRateTemp.Rows.Add(drNew);
                }
                dtRateTemp.TableName="ExChangeRate";
                dsResult.Tables.Add(dtRateTemp);
            }
            catch (Exception ex)
            {
                return jsonResult = "{\"success\":false  ,\"data\":{}   ,\"message\":\"更新汇率失败！\"}";
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
            jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsResult) + "  ,\"message\":\"正常\"}";
            return jsonResult;
        }
    }
}
